<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🔧 Token访问修复验证</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            padding: 30px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #eee;
        }
        
        .test-section {
            margin-bottom: 25px;
            padding: 20px;
            border: 2px solid #e3e3e3;
            border-radius: 8px;
            background: #f8f9fa;
        }
        
        .status-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .status-card {
            padding: 15px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            background: white;
        }
        
        .status-card h4 {
            margin: 0 0 10px 0;
            color: #495057;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .status-value {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            word-break: break-all;
            padding: 8px;
            background: #f8f9fa;
            border-radius: 4px;
        }
        
        .status-success {
            border-color: #28a745;
            background: #f8fff9;
        }
        
        .status-success .status-value {
            color: #155724;
            background: #d4edda;
        }
        
        .status-error {
            border-color: #dc3545;
            background: #fff8f8;
        }
        
        .status-error .status-value {
            color: #721c24;
            background: #f8d7da;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            margin: 5px;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
            transform: translateY(-1px);
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #1e7e34;
            transform: translateY(-1px);
        }
        
        .log-area {
            background: #2c3e50;
            color: #ecf0f1;
            padding: 15px;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
            max-height: 300px;
            overflow-y: auto;
            white-space: pre-wrap;
        }
        
        .fix-summary {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .fix-summary h3 {
            margin: 0 0 15px 0;
            color: #0c5460;
        }
        
        .fix-item {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 8px;
        }
        
        .iframe-preview {
            border: 2px solid #dee2e6;
            border-radius: 8px;
            overflow: hidden;
            height: 500px;
            margin-top: 20px;
        }
        
        .iframe-preview iframe {
            width: 100%;
            height: 100%;
            border: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔧 Token访问修复验证</h1>
            <p>验证用户状态管理和Token访问的修复效果</p>
        </div>

        <!-- 修复总结 -->
        <div class="fix-summary">
            <h3>🎯 修复内容总结</h3>
            <div class="fix-item">
                <span>✅</span>
                <span>修复了 <code>userStore.initAuth is not a function</code> 错误</span>
            </div>
            <div class="fix-item">
                <span>✅</span>
                <span>修复了所有 <code>userStore.token</code> 引用，正确使用 <code>.value</code></span>
            </div>
            <div class="fix-item">
                <span>✅</span>
                <span>修复了所有 <code>userStore.isLoggedIn</code> 引用，正确使用 <code>.value</code></span>
            </div>
            <div class="fix-item">
                <span>✅</span>
                <span>修复了所有 <code>userStore.userInfo</code> 引用，正确使用 <code>.value</code></span>
            </div>
            <div class="fix-item">
                <span>🎯</span>
                <span>现在用户信息应该正常显示，退出登录功能应该可用</span>
            </div>
        </div>

        <!-- 当前状态检查 -->
        <div class="test-section">
            <h3>📊 当前状态检查</h3>
            <div class="status-grid">
                <div class="status-card" id="tokenCard">
                    <h4>🔑 Token状态</h4>
                    <div class="status-value" id="tokenStatus">检查中...</div>
                </div>
                <div class="status-card" id="userCard">
                    <h4>👤 用户信息</h4>
                    <div class="status-value" id="userStatus">检查中...</div>
                </div>
                <div class="status-card" id="loginCard">
                    <h4>🔐 登录状态</h4>
                    <div class="status-value" id="loginStatus">检查中...</div>
                </div>
                <div class="status-card" id="apiCard">
                    <h4>🌐 API状态</h4>
                    <div class="status-value" id="apiStatus">检查中...</div>
                </div>
            </div>
        </div>

        <!-- 测试操作 -->
        <div class="test-section">
            <h3>🧪 功能测试</h3>
            <button class="btn btn-primary" onclick="testLogin()">
                🔐 测试登录功能
            </button>
            <button class="btn btn-success" onclick="testTokenAccess()">
                🔑 测试Token访问
            </button>
            <button class="btn btn-primary" onclick="clearAuthData()">
                🗑️ 清除认证数据
            </button>
            <button class="btn btn-success" onclick="openPortalPage()">
                🏠 打开门户首页
            </button>
        </div>

        <!-- 测试日志 -->
        <div class="test-section">
            <h3>📋 测试日志</h3>
            <div class="log-area" id="logArea">[INFO] Token访问修复验证页面已加载
[INFO] 开始检查修复效果...</div>
        </div>

        <!-- 门户首页预览 -->
        <div class="test-section">
            <h3>🖼️ 修复后的门户首页预览</h3>
            <p>如果修复成功，下面的iframe应该显示正常的门户首页，包括右上角的用户信息</p>
            <div class="iframe-preview">
                <iframe src="http://localhost:5173/home" id="portalIframe"></iframe>
            </div>
        </div>
    </div>

    <script>
        // 日志记录
        function addLog(message, type = 'INFO') {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `[${timestamp}] [${type}] ${message}`;
            
            const logArea = document.getElementById('logArea');
            logArea.textContent += '\n' + logEntry;
            logArea.scrollTop = logArea.scrollHeight;
            
            console.log(logEntry);
        }

        // 更新状态卡片
        function updateCard(cardId, status, isSuccess = true) {
            const card = document.getElementById(cardId);
            const statusDiv = card.querySelector('.status-value');
            
            statusDiv.textContent = status;
            
            if (isSuccess) {
                card.classList.remove('status-error');
                card.classList.add('status-success');
            } else {
                card.classList.remove('status-success');
                card.classList.add('status-error');
            }
        }

        // 检查当前认证状态
        function checkAuthStatus() {
            addLog('检查localStorage中的认证数据...');
            
            const token = localStorage.getItem('campus_token');
            const userInfo = localStorage.getItem('campus_user_info');
            
            // 检查Token状态
            if (token) {
                const tokenInfo = `长度: ${token.length} 字符\n前50字符: ${token.substring(0, 50)}...`;
                updateCard('tokenCard', tokenInfo, true);
                addLog(`✅ Token存在，长度: ${token.length} 字符`);
            } else {
                updateCard('tokenCard', '❌ 未找到Token', false);
                addLog('❌ localStorage中未找到Token');
            }
            
            // 检查用户信息
            if (userInfo) {
                try {
                    const user = JSON.parse(userInfo);
                    const userDetail = `用户名: ${user.username}\n角色: ${user.roleName} (${user.roleCode})\n部门: ${user.departmentName}`;
                    updateCard('userCard', userDetail, true);
                    addLog(`✅ 用户信息存在: ${user.username} (${user.roleCode})`);
                } catch (error) {
                    updateCard('userCard', '❌ 用户信息格式错误', false);
                    addLog('❌ 用户信息JSON解析失败', 'ERROR');
                }
            } else {
                updateCard('userCard', '❌ 未找到用户信息', false);
                addLog('❌ localStorage中未找到用户信息');
            }
            
            // 检查整体登录状态
            if (token && userInfo) {
                updateCard('loginCard', '✅ 已登录状态', true);
                addLog('✅ 用户处于已登录状态');
                return true;
            } else {
                updateCard('loginCard', '❌ 未登录状态', false);
                addLog('❌ 用户处于未登录状态');
                return false;
            }
        }

        // 检查API状态
        async function checkAPIStatus() {
            addLog('检查后端API服务状态...');
            
            try {
                // 测试Mock School API
                const mockResponse = await fetch('http://localhost:48082/mock-school-api/auth/health');
                const mockData = await mockResponse.json();
                
                // 测试主通知服务
                const mainResponse = await fetch('http://localhost:48081/admin-api/test/notification/api/ping');
                const mainData = await mainResponse.text();
                
                const apiInfo = `Mock API: ✅ ${mockData.message}\n主服务: ✅ 响应正常`;
                updateCard('apiCard', apiInfo, true);
                addLog('✅ 所有后端API服务状态正常');
                
                return true;
            } catch (error) {
                const apiError = `❌ API连接失败\n错误: ${error.message}`;
                updateCard('apiCard', apiError, false);
                addLog(`❌ API服务检查失败: ${error.message}`, 'ERROR');
                return false;
            }
        }

        // 测试登录功能
        async function testLogin() {
            addLog('=== 开始测试登录功能 ===');
            
            const loginData = {
                employeeId: 'PRINCIPAL_001',
                name: 'Principal-Zhang',
                password: 'admin123'
            };
            
            try {
                const response = await fetch('http://localhost:48082/mock-school-api/auth/authenticate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json; charset=UTF-8'
                    },
                    body: JSON.stringify(loginData)
                });
                
                if (response.ok) {
                    const data = await response.json();
                    
                    if (data.success) {
                        // 保存认证数据
                        localStorage.setItem('campus_token', data.data.accessToken);
                        localStorage.setItem('campus_user_info', JSON.stringify(data.data));
                        
                        addLog(`✅ 登录测试成功: ${data.data.username}`, 'SUCCESS');
                        
                        // 刷新状态检查
                        checkAuthStatus();
                        
                        // 刷新iframe
                        document.getElementById('portalIframe').src = 'http://localhost:5173/home';
                        addLog('🔄 已刷新门户首页预览');
                        
                    } else {
                        throw new Error(data.message || '登录失败');
                    }
                } else {
                    throw new Error(`HTTP ${response.status}`);
                }
            } catch (error) {
                addLog(`❌ 登录测试失败: ${error.message}`, 'ERROR');
            } finally {
                addLog('=== 登录功能测试完成 ===');
            }
        }

        // 测试Token访问
        function testTokenAccess() {
            addLog('=== 开始测试Token访问 ===');
            
            const token = localStorage.getItem('campus_token');
            
            if (token) {
                addLog(`✅ Token访问正常`);
                addLog(`Token长度: ${token.length} 字符`);
                addLog(`Token格式: ${token.startsWith('eyJ') ? 'JWT格式正确' : 'Unknown格式'}`);
                
                // 尝试解析JWT payload (仅用于测试)
                try {
                    const parts = token.split('.');
                    if (parts.length === 3) {
                        // 注意：这里仅为演示，实际生产环境不应在前端解析JWT
                        addLog(`JWT结构: Header.Payload.Signature`);
                        addLog(`✅ Token格式验证通过`);
                    }
                } catch (error) {
                    addLog(`⚠️ Token格式验证失败: ${error.message}`, 'WARNING');
                }
            } else {
                addLog('❌ 未找到Token，请先登录', 'ERROR');
            }
            
            addLog('=== Token访问测试完成 ===');
        }

        // 清除认证数据
        function clearAuthData() {
            addLog('=== 开始清除认证数据 ===');
            
            localStorage.removeItem('campus_token');
            localStorage.removeItem('campus_user_info');
            
            addLog('✅ 已清除所有认证数据');
            
            // 刷新状态检查
            checkAuthStatus();
            
            // 刷新iframe
            document.getElementById('portalIframe').src = 'http://localhost:5173/home';
            
            addLog('=== 认证数据清除完成 ===');
        }

        // 打开门户页面
        function openPortalPage() {
            addLog('打开门户首页...');
            
            const newWindow = window.open('http://localhost:5173/home', '_blank');
            
            if (newWindow) {
                addLog('✅ 门户首页已在新窗口中打开');
            } else {
                addLog('❌ 无法打开新窗口，请检查弹窗阻止设置', 'WARNING');
                // 刷新iframe作为备用
                document.getElementById('portalIframe').src = 'http://localhost:5173/home';
                addLog('已刷新页面内预览');
            }
        }

        // 页面初始化
        async function initPage() {
            addLog('开始初始化页面...');
            
            // 检查认证状态
            const isLoggedIn = checkAuthStatus();
            
            // 检查API状态
            await checkAPIStatus();
            
            addLog('✅ 页面初始化完成');
            
            if (isLoggedIn) {
                addLog('用户已登录，门户首页应该正常显示用户信息');
                // 延迟刷新iframe
                setTimeout(() => {
                    document.getElementById('portalIframe').src = 'http://localhost:5173/home';
                }, 1000);
            } else {
                addLog('用户未登录，可以点击"测试登录功能"按钮进行测试');
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', initPage);
    </script>
</body>
</html>